package demo.game.chess.client.ui;

import com.allen_sauer.gwt.dnd.client.DragContext;
import com.allen_sauer.gwt.dnd.client.VetoDragException;
import com.allen_sauer.gwt.dnd.client.drop.DropController;
import com.google.gwt.user.client.ui.Widget;

public class ChessPieceDropController implements DropController {

	private final ChessCellUI target;

	ChessBoardUI boardUI;

	/**
	 * @param dropTarget the grid cell.
	 */
	public ChessPieceDropController(final ChessBoardUI boardUI,
			final ChessCellUI dropTarget) {
		this.boardUI = boardUI;
		this.target = dropTarget;
	}

	@Override
	public Widget getDropTarget() {
		return this.target;
	}

	@Override
	public void onDrop(final DragContext context) {
		// Log.debug(this.getClass() + " onDrop target=" + this.target);
		this.boardUI.getMoveValidator().onDropPieceAt(this.target);
	}

	@Override
	public void onEnter(final DragContext context) {
		// Log.debug(this.getClass() + " onEnter target=" + this.target);
		this.boardUI.getMoveValidator().setDndMode(true);
		this.boardUI.getMoveValidator().selectPiece(
				(ChessPieceUI) context.draggable);
		this.boardUI.getMoveValidator().onMouseIn(this.target);

	}

	@Override
	public void onLeave(final DragContext context) {
		// Log.debug(this.getClass() + " onLeave target=" + this.target);
		this.boardUI.getMoveValidator().onMouseOut(this.target);
		this.boardUI.getMoveValidator().setDndMode(false);

	}

	@Override
	public void onMove(final DragContext context) {
	}

	@Override
	public void onPreviewDrop(final DragContext context)
			throws VetoDragException {
		//Log.debug(this.getClass() + " onPreviewDrop target=" + this.target);
		if (!this.boardUI.getMoveValidator().canDropPieceAt(this.target)) {
			throw new VetoDragException();
		}
	}
}
